package com.yg.controller;


import com.yg.pojo.TBook;
import com.yg.service.TBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kotori
 * @since 2022-11-18
 */
@RestController
@RequestMapping("/book")
public class TBookController {
    @Autowired
    private TBookService bookService;


    @PostMapping("/update")
    public void update(HttpSession session, HttpServletResponse response, @RequestParam("pageNo") String pageNo, @RequestParam("pageSize") String pageSize, @RequestParam("id") Integer id, @RequestParam("name") String name, @RequestParam("price") String price, @RequestParam("author") String author, @RequestParam("sales") Integer sales, @RequestParam("stock") Integer stocks) throws IOException {
        String user = (String) session.getAttribute("loginUser");
        if (user != null) {
            TBook book = new TBook(id, name, new BigDecimal(price), author, sales, stocks, null);
            bookService.updateById(book);
            response.sendRedirect("/manager/book/page/" + pageNo + "/" + pageSize);
        } else {
            response.sendRedirect("/login");
        }
    }

    @GetMapping("/remove/{bookId}/{pageNo}/{pageSize}")
    public void remove(@PathVariable("pageNo") Long pageNo, @PathVariable("pageSize") Long pageSize, @PathVariable("bookId") String bookId, HttpSession session, HttpServletResponse response) throws IOException {
        String user = (String) session.getAttribute("loginUser");
        if (user != null) {
            bookService.removeById(bookId);
            response.sendRedirect("/manager/book/page/" + pageNo + "/" + pageSize);
        } else {
            response.sendRedirect("/login");
        }
    }

    @PostMapping("/add")
    public void add(HttpSession session, HttpServletResponse response, @RequestParam("name") String name, @RequestParam("price") String price, @RequestParam("author") String author, @RequestParam("sales") Integer sales, @RequestParam("stock") Integer stocks) throws IOException {
        String user = (String) session.getAttribute("loginUser");
        if (user != null) {
            TBook book = new TBook(null, name, new BigDecimal(price), author, sales, stocks, null);
            bookService.save(book);
            response.sendRedirect("/manager/book/");
        } else {
            response.sendRedirect("/login");
        }
    }
}

